package dbutils

import (
	"database/sql"
	"fmt"
	"strings"
)

func BuildInsertSQL(tableName string, columns, updateColumns []string) string {

	// 构造 INSERT 部分
	placeholder := strings.Repeat("?, ", len(columns)-1) + "?"
	insertSQL := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", tableName, strings.Join(columns, ", "), placeholder)

	// 构造 ON DUPLICATE KEY UPDATE 部分
	updateExpr := make([]string, len(updateColumns))
	for i, col := range updateColumns {
		updateExpr[i] = fmt.Sprintf("%s = VALUES(%s)", col, col)
	}
	finalSQL := fmt.Sprintf("%s ON DUPLICATE KEY UPDATE %s", insertSQL, strings.Join(updateExpr, ", "))

	return finalSQL
}

func GetLocalhostConnect() (*sql.DB, error) {
	db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/stock?parseTime=true")
	if err != nil {
		fmt.Println("无法打开数据库:", err)
		return nil, err
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		fmt.Println("无法连接到数据库:", err)
		return nil, err
	}
	return db, err
}

func GetConnect(user, pwd, ip, port, dbname string) (*sql.DB, error) {
	db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", user, pwd, ip, port, dbname))
	if err != nil {
		fmt.Println("无法打开数据库:", err)
		return nil, err
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		fmt.Println("无法连接到数据库:", err)
		return nil, err
	}
	return db, err
}
